package com.aiyige.page.my;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.db.dao.DownloadModelDao;
import com.aiyige.base.db.table.DownloadModel;
import com.aiyige.base.eventbus.EventBalanceChanged;
import com.aiyige.base.eventbus.EventRemovalSuccess;
import com.aiyige.model.User;
import com.aiyige.page.my.download.util.DownloadUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 我的
 */
public class MyPage extends BaseFragment {
    public static final String TAG = MyPage.class.getSimpleName();
    public static final int MESSAGE_LEVEL = 0;
    @BindView(R.id.parallaxView)
    View parallaxView;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;
    int mOffset = 0;
    int mScrollY = 0;
    int mFooterOffset = 0;
    @BindView(R.id.userNameTv)
    TextView userNameTv;
    @BindView(R.id.genderIv)
    ImageView genderIv;
    @BindView(R.id.avatarIv)
    CircleImageView avatarIv;
    @BindView(R.id.verifyIv)
    ImageView verifyIv;
    @BindView(R.id.myMoreIv)
    ImageView myMoreIv;
    @BindView(R.id.loginRegisterTv)
    TextView loginRegisterTv;
    @BindView(R.id.clickLoginTv)
    TextView clickLoginTv;
    @BindView(R.id.notLoginLayout)
    LinearLayout notLoginLayout;
    @BindView(R.id.userNameLayout)
    RelativeLayout userNameLayout;
    @BindView(R.id.followNumTv)
    TextView followNumTv;
    @BindView(R.id.fanNumTv)
    TextView fanNumTv;
    @BindView(R.id.loginLayout)
    LinearLayout loginLayout;
    @BindView(R.id.myLayout)
    RelativeLayout myLayout;
    @BindView(R.id.dynamicDisplayTv)
    TextView dynamicDisplayTv;
    @BindView(R.id.dynamicDisplayLayout)
    LinearLayout dynamicDisplayLayout;
    @BindView(R.id.myFavoriteTv)
    TextView myFavoriteTv;
    @BindView(R.id.myFavoriteLayout)
    LinearLayout myFavoriteLayout;
    @BindView(R.id.videoDownloadTv)
    TextView videoDownloadTv;
    @BindView(R.id.videoDownloadLayout)
    LinearLayout videoDownloadLayout;
    @BindView(R.id.viewHistoryTv)
    TextView viewHistoryTv;
    @BindView(R.id.viewHistoryLayout)
    LinearLayout viewHistoryLayout;
    @BindView(R.id.myTaskTv)
    TextView myTaskTv;
    @BindView(R.id.myTaskLayout)
    RelativeLayout myTaskLayout;
    @BindView(R.id.myWalletTv)
    TextView myWalletTv;
    @BindView(R.id.balanceLayout)
    LinearLayout balanceLayout;
    @BindView(R.id.myWalletLayout)
    RelativeLayout myWalletLayout;
    @BindView(R.id.myBuyTv)
    TextView myBuyTv;
    @BindView(R.id.waitingPayOrderLayout)
    LinearLayout waitingPayOrderLayout;
    @BindView(R.id.myBuyLayout)
    RelativeLayout myBuyLayout;
    @BindView(R.id.mySellTv)
    TextView mySellTv;
    @BindView(R.id.sellAmountLayout)
    LinearLayout sellAmountLayout;
    @BindView(R.id.mySellLayout)
    RelativeLayout mySellLayout;
    @BindView(R.id.personalProfileTv)
    TextView personalProfileTv;
    @BindView(R.id.personalProfileLayout)
    RelativeLayout personalProfileLayout;
    @BindView(R.id.settingTv)
    TextView settingTv;
    @BindView(R.id.settingLayout)
    RelativeLayout settingLayout;
    @BindView(R.id.balanceTv)
    TextView balanceTv;
    @BindView(R.id.waitingPayOrderTv)
    TextView waitingPayOrderTv;
    @BindView(R.id.sellAmountTv)
    TextView sellAmountTv;
    @BindView(R.id.preferentialTv)
    TextView preferentialTv;
    long downloadVideoNum = 0;
    @BindView(R.id.preferentialLayout)
    LinearLayout preferentialLayout;


    public static MyPage newInstance() {
        MyPage fragment = new MyPage();
        fragment.setAutoRegisterEventBus(true);
        return fragment;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventRefresh(EventRemovalSuccess eventRemovalSuccess) {
        if (!isFirstLoad() && isFragmentVisible()) {
            new RequestDataTask().execute();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventRefresh(EventBalanceChanged event) {
        if (event != null && balanceTv != null) {
            balanceTv.setText(StringUtils.priceFormat(AccountUtil.getBalance()));
        }
    }



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page_my, container, false);
        unbinder = ButterKnife.bind(this, view);
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshLayout) {

            }
        });
        refreshLayout.setEnableOverScrollDrag(false);
        refreshLayout.setEnableOverScrollBounce(false);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadmore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                new RequestDataTask().execute();
            }
        });
        refreshLayout.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onHeaderPulling(RefreshHeader header, float percent, int offset, int bottomHeight, int extendHeight) {
                mOffset = offset;
                parallaxView.setTranslationY(mOffset - mScrollY);
            }

            @Override
            public void onHeaderReleasing(RefreshHeader header, float percent, int offset, int bottomHeight, int extendHeight) {
                mOffset = offset;
                parallaxView.setTranslationY(mOffset - mScrollY);
            }

            @Override
            public void onFooterPulling(RefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight) {
                mFooterOffset = offset;
            }

            @Override
            public void onFooterReleasing(RefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight) {
                mFooterOffset = offset;

            }
        });
        refreshLayout.setEnableLoadmore(false);
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                mScrollY = scrollY;
                parallaxView.setTranslationY(mOffset - mScrollY);
            }
        });
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        if (!isFirstLoad() && isFragmentVisible()) {
            new RequestDataTask().execute();
        }
    }

    @Override
    protected void onVisible() {
        if (!isFirstLoad()) {
            new RequestDataTask().execute();
        }
        super.onVisible();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }





    @Override
    protected void initData() {
        new RequestDataTask().execute();
    }

    @OnClick({R.id.couponLayout, R.id.avatarIv, R.id.notLoginLayout, R.id.loginLayout, R.id.dynamicDisplayLayout, R.id.myFavoriteLayout, R.id.videoDownloadLayout, R.id.viewHistoryLayout, R.id.myTaskLayout, R.id.myWalletLayout, R.id.myBuyLayout, R.id.mySellLayout, R.id.personalProfileLayout, R.id.settingLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.couponLayout:
                if (AccountUtil.isLogin()) {
                    ARouter.getInstance()
                            .build(ARouterConfig.UserCouponPage)
                            .navigation();
                } else {

                }
                break;
            case R.id.avatarIv:
                if (AccountUtil.isLogin()) {
                    ARouter.getInstance()
                            .build(ARouterConfig.UserPage)
                            .withString("userId", AccountUtil.getCurrentUser().getId())
                            .navigation();
                } else {
                    ARouter.getInstance()
                            .build(ARouterConfig.LoginPage)
                            .navigation();
                }
                break;
            case R.id.notLoginLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.LoginPage)
                        .navigation();
                break;
            case R.id.loginLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.UserPage)
                        .withString("userId", AccountUtil.getCurrentUser().getId())
                        .navigation();
                break;
            case R.id.dynamicDisplayLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.DMPage)
                        .navigation();
                break;
            case R.id.myFavoriteLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.MyFavoritePage)
                        .navigation();
                break;
            case R.id.videoDownloadLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.MyDownloadPage)
                        .navigation();
                break;
            case R.id.viewHistoryLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.MyViewPage)
                        .navigation();
                break;
            case R.id.myTaskLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.MyBuyPage)
                        .navigation();
                break;
            case R.id.myWalletLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.WalletHomePage)
                        .navigation();
                break;
            case R.id.myBuyLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.MyOrderListPage)
                        .navigation();
                break;
            case R.id.mySellLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.MySellPage)
                        .navigation();
                break;
            case R.id.personalProfileLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.EditUserInfoPage)
                        .navigation();
                break;
            case R.id.settingLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.SettingsPage)
                        .navigation();
//                List<VideoCacheParentModel> list =  RemovalHandler.getInstance().getAllList();
//                if (!ListUtil.isEmpty(list)) {
//                    ToastX.show("find old videoCache :" + list.size() + "");
//                } else {
//                    ToastX.show("no cache");
//                }
                break;
        }
    }


    private class RequestDataTask extends AsyncTask<Object, Object, Object> {

        @Override
        protected void onPreExecute() {
            if (AccountUtil.isLogin()) {
                try {
                    downloadVideoNum = DownloadModelDao.getDao().queryBuilder()
                            .where()
                            .eq(DownloadModel.USER_ID_FIELD, AccountUtil.getCurrentUser().getId())
                            .and()
                            .ne(DownloadModel.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE)
                            .and()
                            .ne(DownloadModel.CONTROL_OPTION_FIELD, DownloadUtil.CONTROL_OPTION_DELETE_RECORD_ONLY)
                            .countOf();
                } catch (Exception e) {

                }
            }
            updateView();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                if (AccountUtil.isLogin()) {
                    Response<ResponseBody> response = ApiManager.getService()
                            .userCenterUsers(AccountUtil.getCurrentUser().getId())
                            .execute();
                    if (response.code() != ResponseCode.OK) {
                        throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                    }
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    User tempUser = JSON.parseObject(json, User.class);
                    User user = AccountUtil.getCurrentUser();
                    user.update(tempUser);
                    AccountUtil.updateCurrentUser(user);
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            if (refreshLayout != null) {
                refreshLayout.finishRefresh();
            }
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                updateView();
            }
        }

    }

    public void updateView() {
        User user = AccountUtil.getCurrentUser();
        if (AccountUtil.isLogin()) {
            myMoreIv.setVisibility(View.VISIBLE);
            loginLayout.setVisibility(View.VISIBLE);
            notLoginLayout.setVisibility(View.INVISIBLE);
            userNameTv.setText(user.getAccount());
            switch (user.getMoreBackup().getSex()) {
                case User.GENDER_FEMALE:
                    genderIv.setVisibility(View.VISIBLE);
                    genderIv.setImageResource(R.drawable.personal_girl);
                    break;
                case User.GENDER_MALE:
                    genderIv.setVisibility(View.VISIBLE);
                    genderIv.setImageResource(R.drawable.personal_boy);
                    break;
                case User.GENDER_UNKNOWN:
                    genderIv.setVisibility(View.INVISIBLE);
                    break;
            }
            followNumTv.setText(StringUtils.formatNum(user.getStatisticsBackup().getFollowCount()));
            fanNumTv.setText(StringUtils.formatNum(user.getStatisticsBackup().getFollowersCount()));
            dynamicDisplayTv.setText(StringUtils.formatNum(user.getStatisticsBackup().getDynamicCount()));
            myFavoriteTv.setText(StringUtils.formatNum(user.getStatisticsBackup().getFavoriteCount()));
            videoDownloadTv.setText(String.valueOf(downloadVideoNum));
            viewHistoryTv.setText(StringUtils.formatNum(user.getStatisticsBackup().getBrowseCount()));
            balanceLayout.setVisibility(View.VISIBLE);
            waitingPayOrderLayout.setVisibility(View.VISIBLE);
            sellAmountLayout.setVisibility(View.VISIBLE);
            preferentialLayout.setVisibility(View.VISIBLE);
            balanceTv.setText(StringUtils.priceFormat(user.getStatisticsBackup().getPurseBalance()));
            waitingPayOrderTv.setText(StringUtils.formatNum(user.getStatisticsBackup().getWaitPayCount()));
            sellAmountTv.setText(StringUtils.priceFormat(user.getStatisticsBackup().getTransactionAmount()));
            preferentialTv.setText(String.valueOf(user.getStatisticsBackup().getCouponCount()));
            GlideUtil.with(getActivity())
                    .loadAvatar(user.getAvatar())
                    .into(avatarIv);
        } else {
            myMoreIv.setVisibility(View.INVISIBLE);
            loginLayout.setVisibility(View.INVISIBLE);
            notLoginLayout.setVisibility(View.VISIBLE);
            avatarIv.setImageResource(R.drawable.default_head);
            balanceLayout.setVisibility(View.INVISIBLE);
            waitingPayOrderLayout.setVisibility(View.INVISIBLE);
            sellAmountLayout.setVisibility(View.INVISIBLE);
            preferentialLayout.setVisibility(View.INVISIBLE);
            dynamicDisplayTv.setText("0");
            myFavoriteTv.setText("0");
            videoDownloadTv.setText("0");
            viewHistoryTv.setText("0");
            preferentialTv.setText("0");
        }
    }


}
